package com.sjs.boot.dynamic.init;

import com.sjs.boot.dynamic.core.config.method.MethodConfig;
import com.sjs.boot.dynamic.core.config.method.Methods;
import com.sjs.boot.dynamic.facade.AbstractInitializer;
import com.sjs.boot.dynamic.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.Serializable;

/**
 * @author uto_dev_008
 * @desc 请求参数初始化
 * @since 2021/12/31 14:31
 */
@Configuration
public class RequestInitListener implements Serializable {
    protected AbstractInitializer initializer = null;
    private static final Logger LOG = LoggerFactory.getLogger(RequestInitListener.class);
    public RequestInitListener() {
        initializer = new RequestInit();
    }
    private static String configRootPath = "";
    private static String webRoot = "/";

    @PostConstruct
    public void contextInitialized() {

        configRootPath =  PropertiesUtil.getString("application.web-cfg.location");
        //需确保在Jfinal配置后
        if (webRoot == null) {
            webRoot = PropertiesUtil.getString("server.servlet.context-path", "/");
        }

        initializer.setAppInitializer(new AbstractInitializer.AppInitializer() {
            @Override
            public int init(String configPath) {

                MethodConfig.init();
                if (!Methods.init(new File(configPath + "web-cfg"))) {
                    LOG.error("Fail to parse methods");
                    return 8;
                }
                return 0;
            }
            @Override
            public void destroy() {
                Methods.destroy();
            }
        });

        int retCode = initializer.init(configRootPath);
        if (retCode != 0) {
            LOG.error("Fail to call ServletInit, retCode {}", retCode);
            System.exit(retCode);
        }
    }


    protected static class RequestInit extends AbstractInitializer {
        @Override
        protected int beforeInit(String configPath) {
            return 0;
        }

        @Override
        protected int afterInit(String configPath) {
            return 0;
        }

        @Override
        protected void destroy() {
        }
    }
}
